package com.kehao.accountbook.network;

import android.app.Application;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kehao.accountbook.AccountApplication;
import com.kehao.accountbook.pojo.Expenditure;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;

import okhttp3.*;

public class Network {
    AccountApplication application;
    public static Handler handler =null;
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    public static final String LOGIN_URL = "http://192.168.0.110:8080/account/login";
    public static final String REGISTER_URL = "http://192.168.0.110:8080/account/register";//register
    public static final String CHANGE_PASSWORD_URL = "http://192.168.0.110:8080/account/changepassword";

    private static OkHttpClient okHttpClient = new OkHttpClient();
    private TwoCaseCallBack callBack ;
    private String json;
    private String url;

    public Network(TwoCaseCallBack twoCaseCallBack, String json, String url, AccountApplication application){
        this.callBack = twoCaseCallBack;
        this.json = json;
        this.url = url;
        this.application = application;
    }


    public void send(){
        RequestBody requestBody = RequestBody.create(json,JSON);
        Request request = new Request.Builder().url(this.url).post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
               callBack.fail();
               application.modeOffline();
               if(handler!=null){
                   Message message = new Message();
                   message.what=1;
                   handler.sendMessage(message);
               }
                Log.e("Net", "fail" );
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                callBack.success(response.body().string());
                application.modeOnline();
                if(handler!=null){
                    Message message = new Message();
                    message.what=1;
                    handler.sendMessage(message);
                }
                Log.e("Net", "success" );
            }
        });
    }



}
